package com.you.netty.connection;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.atomic.AtomicLong;

public class Client {

    private static final String SERVER_HOST = "127.0.0.1";

    public static AtomicLong connectNum = new AtomicLong(0); //连接次数统计

    public static void main(String[] args) {

        int beginPort = 8000;
        int endPort = 8010;

        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        final Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_REUSEADDR, true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
            }
        });
        //循环不断的连接服务端
        int index = 0;
        while (!Thread.interrupted()) {
            final int port = beginPort + index;
            try {
                ChannelFuture channelFuture = bootstrap.connect(SERVER_HOST, port);
                //连接后监听事件
                channelFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            System.out.println("connect failed, port is : " + port);
                        } else {
                            connectNum.getAndAdd(1);
                            System.out.println("connected success, port is : " + port + ",连接数是：" + connectNum.get());
                            //连接完，关闭当前连接
                            //channelFuture.channel().close();
                        }
                    }
                });
                channelFuture.get();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            if (port == endPort - 1) {
                index = 0;
                try {
                    Thread.sleep(1000 * 100);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            } else {
                index++;
            }
        }
    }
}
